function sleep(delay) {
  for (let now = Date.now(); Date.now() - now < delay; ) {}
}
let A1 = { type: "div", key: "A1" };
let B1 = { type: "div", key: "B1", return: A1 };
let B2 = { type: "div", key: "B2", return: A1 };
let C1 = { type: "div", key: "C1", return: B1 };
let C2 = { type: "div", key: "C2", return: B1 };
A1.child = B1;
B1.sibling = B2;
B1.child = C1;
C1.sibling = C2;

let nextUnitOfWork = null; // 下一个执行单元
let startTime = Date.now();
function workLoop(deadline) {
  while (
    (deadline.timeRemaining() > 0 || deadline.didTimeout) &&
    nextUnitOfWork
  ) {
    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
  }
  if (!nextUnitOfWork) {
    console.log("time", Date.now() - startTime);
    console.log("render阶段结束");
  } else {
    requestIdleCallback(workLoop, { timeout: 1000 });
  }
}
function performUnitOfWork(fiber) {
  beginWork(fiber);
  if (fiber.child) {
    //如果有子，返回第一个子节点
    return fiber.child;
  }
  while (fiber) {
    completeUnitOfWork(fiber);
    if (fiber.sibling) {
      return fiber.sibling;
    }
    fiber = fiber.return;
  }
}
function completeUnitOfWork(fiber) {
  console.log(fiber.key, "end");
}
function beginWork(fiber) {
  sleep(20);
  console.log(fiber.key, "start");
}
nextUnitOfWork = A1;
requestIdleCallback(workLoop, { timeout: 0 });
